#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import threadpool
import xml.etree.ElementTree as ET

class FileParserManager:
    """负责Android工程资源文件目录内容解析"""

    def __init__(self,fileName):
        '''
        fileName  工程中tmp目录下面的Android资源目录的名称，例如res,res2等
        '''
        self.mFileName = fileName
        self.mResFilePath = os.environ["OAS_PATH"] + os.path.sep + "tmp" + os.path.sep +  self.mFileName


    def prepare(self,*stringFileName):
        '''
        准备开始解析
        stringFileName 字符串文件名称，例如strings，sprd_string等。可以为空，为空的话默认只解析strings.xml文件内容
        '''
        if len(stringFileName) == 0:
            stringFileName = ("strings.xml")
        self.mTargetStringFileName = stringFileName
        self.mAllValueDirResult = self.getAllValuesDir()


    def start(self,stringDatabaseManager,threadCount=8):
        '''
        开始使用现成来解析和存储翻译数据
        threadCount  线程池大小，默认是8
        stringDatabaseManager 数据库管理对象，用来插入数据的
        '''
        self.mSDM = stringDatabaseManager
        pool = threadpool.ThreadPool(threadCount) 
        requests = threadpool.makeRequests(self.parserXml, self.mAllValueDirResult) 
        [pool.putRequest(req) for req in requests] 
        pool.wait() 


    def parserXml(self,valuePath):
       '''
       解析给出xml文件内容
       valuePath xml的文件路径
       '''
       self.preXliffTag(valuePath);   #将文本中的xliff标签掩盖起来，该标签只是用来替换的，不涉及到翻译
       langCat = self.getLangCategory(valuePath)   #获取该文件的语言类型
       #print "directory is:" + valuePath + ";language classify is:" + langCat
       tree = ET.ElementTree(file=valuePath)
       root = tree.getroot()
       for child_of_root in root:
            if child_of_root.tag == "string":   #解析字符串,resType=1
                # print "node string================="
                # print child_of_root.attrib,child_of_root.text
                self.mSDM.save(child_of_root,langCat)
            elif child_of_root.tag == "string-array":   #解析字符串数组,resType=2
                print "node string-array================="
            elif child_of_root.tag == "plurals":        #解析大致数,resType=3
                print "node plurals================="
            else:
                print u"未知tag=>" + child_of_root.tag


    def getLangCategory(self,valuePath):
        '''
        获取字符文件的语言类别
        如果是values.xml 则返回defalut，表明是默认的
        比如en,in,zh_rCN都代表一个国家和地区的语言类别
        '''
        dirName = os.path.dirname(valuePath)
        pos = dirName.rfind("values")
        cate = dirName[pos+7:]
        if cate.strip()=="":  
            return "default"
        else:
            return cate


    def preXliffTag(self,valuePath):
        '''
        将该文件中的xliff属性替换掉，避免xml化
        前面的剪头替换为x后面的替换为e
        valuePath 字符文件的路径
        '''
        with open(valuePath,'r+') as f:
            t = f.read()
            t = t.replace('<xliff:', 'xxliff:')
            t = t.replace('</xliff', 'exliff:')
            f.seek(0, 0)    
            f.write(t)


    def getAllValuesDir(self):
        '''
        获取所有的values目录，因为需要翻译的字符文件都在该目录下面
        '''
        dirs = os.listdir(self.mResFilePath)
        for dirName in dirs:
            nowDir = self.mResFilePath + os.path.sep +  dirName
            if os.path.isdir(nowDir) and dirName.startswith("values"):
                #print ">>>" + nowDir
                stringsDir = os.listdir(nowDir)
                for stringFile in stringsDir:
                    stringPath = nowDir + os.path.sep + stringFile
                    #print ">>>" + stringFile 
                    if os.path.isfile(stringPath) and (stringFile in self.mTargetStringFileName):
                        yield stringPath
 

    def __del__(self):
    	'''
    	在销毁的时候将数据库管理引用也取消引用
    	'''
        del self.mSDM
